package com.wzl.myviewgroup.flow;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.InputFilter;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.wzl.myviewgroup.R;
import com.wzl.myviewgroup.utils.SizeUtils;

import java.util.ArrayList;
import java.util.List;


public class FlowLayout extends ViewGroup {

    public static final int DEFAULT_LINE =3;
    //后需要转单位，目前是px不适配
    public static final int DEFAULT_HORIZONTAL_MARGIN= SizeUtils.dip2px(5f);
    public static final int DEFAULT_VERTICAL_MARGIN =SizeUtils.dip2px(5f);;
    public static final int DEFAULT_BORDER_RADIUS=SizeUtils.dip2px(5f);;
    public static final int DEFAULT_TEXT_MAX_LENGTH = -1;
    private static final String TAG ="FlowLayout";
    private int MaxLines;
    private float mHorizontalMargin;
    private float mVerticalMargin;
    private int mTextMaxLength;
    private int mTextColor;
    private int mBordercolor;
    private float mBorderRadius;

    private List<String> mData = new ArrayList<>();
    private OnItemClickListener mItemClickListener=null;


    public FlowLayout(Context context) {
        this(context,null);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        //获取属性
        TypedArray a =context.obtainStyledAttributes(attrs, R.styleable.FlowLayout);
//maxLine
        MaxLines =a.getInt(R.styleable.FlowLayout_maxLine,DEFAULT_LINE);
        if(MaxLines!=-1&&MaxLines<1){
            throw new IllegalArgumentException("maxLine must be >=1");
        }
 //itemHorizontalMargin
        mHorizontalMargin =a.getDimension(R.styleable.FlowLayout_itemHorizontalMargin,DEFAULT_HORIZONTAL_MARGIN);
                //itemVerticalMargin
        mVerticalMargin =a.getDimension(R.styleable.FlowLayout_itemVerticalMargin,DEFAULT_VERTICAL_MARGIN);
        //textMaxLength
        mTextMaxLength =a.getInt(R.styleable.FlowLayout_textMaxLength,DEFAULT_TEXT_MAX_LENGTH);
        if(mTextMaxLength!=-1&&mTextMaxLength<0){
            throw new IllegalArgumentException("textMaxLength must be >=0");
        }
 //textColor
        mTextColor =a.getColor(R.styleable.FlowLayout_textColor,getResources().getColor(R.color.text_grey));
        //borderColor
        mBordercolor =a.getColor(R.styleable.FlowLayout_bordercolor,getResources().getColor(R.color.text_grey));
        //borderRadio
        mBorderRadius =a.getDimension(R.styleable.FlowLayout_borderRadius,DEFAULT_BORDER_RADIUS);

        Log.d(TAG,"mMaxLines ==>"+MaxLines);
        Log.d(TAG,"mHorizontalMargin ==>"+mHorizontalMargin);
        Log.d(TAG,"mVerticalMargin ==>"+mVerticalMargin);
        Log.d(TAG,"mTextMaxLength ==>"+mTextMaxLength);
        Log.d(TAG,"mTextColor ==>"+mTextColor);
        Log.d(TAG,"mBordercolor ==>"+mBordercolor);
        Log.d(TAG,"mBorderRadius ==>"+mBorderRadius);
        //回收TypedArray,回收后不能再使用,否则会报错
        a.recycle();
    }

    public void setTextList(List<String>data){
        this.mData.clear();
        this.mData.addAll(data);
        //根据数据创建子View,并且添加进来
        setUpChildren();
    }

    private void setUpChildren(){
        //先清空原来的内容
        removeAllViews();
        //添加子View进来
        for(String datum :mData){
//            TextView textView =new TextView(getContext());

            //使用布局填充器,将布局文件(xml)转化为View对象,添加到ViewGroup中
            //attachToRoot 参数为true,表示将布局文件转化为View对象后,直接添加到ViewGroup中
            //attachToRoot 参数为false,表示将布局文件转化为View对象后,需要手动添加到ViewGroup中
            TextView textView = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.item_flow_text, this, false);
            //设置文本内容长度
            /*if(mTextMaxLength !=DEFAULT_TEXT_MAX_LENGTH && datum.length() >mTextMaxLength){
                    textView.setText(datum.substring(0,mTextMaxLength));
            }else {
                textView.setText(datum);
            }*/
            if(mTextMaxLength !=DEFAULT_TEXT_MAX_LENGTH) {
                textView.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mTextMaxLength)});
            }
            textView.setText(datum);

            //TODO:设置TextView的相关属性：边距，颜色，border之类..
            final String data =datum;
            textView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d(TAG,"click");
                    if(mItemClickListener !=null){
                        mItemClickListener.onItemClickListener(v,data);
                }
            }});

            addView(textView);
        }
    }

    public void setOnItemClickListener(final OnItemClickListener listener){
        this.mItemClickListener =listener;
    }

    public interface OnItemClickListener{
        void onItemClickListener(View v,String text);
    }


     /*
      *这两值来自于父控件，包合值和模式
      *int类型 ==> 4字节 ==> 4*8 bit ==>32
      *0 ==>0
      * *1 ===>1
      * *2 ===>10
      * *3 ===>11
            I
      param
      pavam heightMeasurespec
      */

    private  List<List> mLines = new ArrayList<>();

    //测量自己,测量孩子
    //widthMeasureSpec:宽度模式，高度模式
    //heightMeasureSpec:宽度大小，高度大小
    @Override
    protected void onMeasure(int widthMeasurespec,int heightMeasurespec){
        super.onMeasure(widthMeasurespec,heightMeasurespec);
        //获取模式
        int mode =MeasureSpec.getMode(widthMeasurespec);
        //获取大小
        int parentWidthSize =MeasureSpec.getSize(widthMeasurespec);
        int parnetHeightSize =MeasureSpec.getSize(heightMeasurespec);
        Log.d(TAG,"mode ==>"+mode);
        Log.d(TAG,"parentWidthSize ==>"+parentWidthSize);
        Log.d(TAG,"parnetHeightSize ==>"+parnetHeightSize);
        Log.d(TAG,"AT_MOST"+MeasureSpec.AT_MOST);
        Log.d(TAG,"EXACTLY"+MeasureSpec.EXACTLY);
        Log.d(TAG,"UNSPECIFIED"+MeasureSpec.UNSPECIFIED);

        int childcount =getChildCount();
        if(childcount == 0){
            return;
        }
        //先清空
        mLines.clear();
        //添加默认行
        List<View> line =new ArrayList<>();
        mLines.add(line);
        //测量孩子
        //先测量孩子，然后判断是否可以添加到当前行
        //如果可以添加，则添加进去
        //如果不可以添加，则新建一行
        int childWidthSpace =MeasureSpec.makeMeasureSpec(parentWidthSize,MeasureSpec.AT_MOST);
        int childHeightSpace =MeasureSpec.makeMeasureSpec(parentWidthSize,MeasureSpec.AT_MOST);

        for(int i=0;i<childcount;i++){
            View child =getChildAt(i);
            if(child.getVisibility()!=VISIBLE){
                continue;
            }
            //测量孩子，
            //measureChild
            measureChild(child,childWidthSpace,childHeightSpace);
            if(line.size()==0){
                //可以添加
                line.add(child);
            }else {
                //判断是否可以添加到当前行
                boolean canBeAed =checkChildCanBeAdd(line,child,parentWidthSize);
                if(!canBeAed){
                    if(MaxLines!=-1&& mLines.size()>=MaxLines){
                        break;
                    }
                    line =new ArrayList<>();
                    mLines.add(line);
                }
                line.add(child);
            }
        }
        //根据尺寸计算所有行高
        View child =getChildAt(0);
        int childHeight =child.getMeasuredHeight();
        int parentHeightTargetsize = (int) (childHeight * mLines.size()+
                (mLines.size()+1)*mVerticalMargin)+
                (mLines.size()+1)*getPaddingTop()+(mLines.size()+1)*getPaddingBottom();

        //测量自己
        setMeasuredDimension(parentWidthSize,parentHeightTargetsize);

    }
    //判断是否可以添加
    //line:当前行
    private boolean checkChildCanBeAdd(List<View> line,View child,int parentwidthsize){
        int measuredwidth =child.getMeasuredWidth();
        int totalwidth =0;
        for(View view :line){
            totalwidth +=view.getMeasuredWidth()+mHorizontalMargin+getPaddingLeft()+getPaddingRight();
        }
        totalwidth +=measuredwidth+mHorizontalMargin+mHorizontalMargin;
        //如果超出限制宽度，则不可以再添加
        //否则可以添加
        return totalwidth <= parentwidthsize;
    }
    //布局,布局孩子
    //l,t,r,b
    //l:左上角x坐标
    //t:左上角y坐标
    //r:右下角x坐标
    //b:右下角y坐标
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        View fistchild =getChildAt(0);
        int currentleft = (int) mHorizontalMargin+getPaddingLeft();
        int currentIop = (int) mVerticalMargin+getPaddingTop();
        int currentRight = (int) mHorizontalMargin+getPaddingLeft();
        int currentBottom = (int) (fistchild.getMeasuredHeight()+mVerticalMargin)+getPaddingBottom();
        for(List<View>line :mLines){
            for(View view :line){
            //布局每一行
                int width =view.getMeasuredWidth();
                int height =view.getMeasuredHeight();
                currentRight +=width;
                //判断右边界是否超出
                if(currentRight>r-mHorizontalMargin-getPaddingLeft()){
                    currentRight= (int) (r-mHorizontalMargin-getPaddingLeft());
                }
                // 布局孩子
                view.layout(currentleft,currentIop,currentRight,currentBottom);
                currentleft = (int) (currentRight+mHorizontalMargin)+getPaddingLeft();
                currentRight += (int) mHorizontalMargin+getPaddingRight();
            }
            currentleft = (int) mHorizontalMargin+getPaddingLeft();
            currentRight =(int) mHorizontalMargin+getPaddingRight();
            currentBottom +=fistchild.getMeasuredHeight()+mVerticalMargin+getPaddingBottom();
            currentIop +=fistchild.getMeasuredHeight()+mVerticalMargin+getPaddingTop();
        }

    }

    public int getMaxLines() {
        return MaxLines;
    }

    public void setMaxLines(int maxLines) {
        MaxLines = maxLines;
    }

    public float getmHorizontalMargin() {
        return mHorizontalMargin;
    }

    public void setmHorizontalMargin(float mHorizontalMargin) {
        this.mHorizontalMargin = mHorizontalMargin;
    }

    public float getmVerticalMargin() {
        return mVerticalMargin;
    }

    public void setmVerticalMargin(float mVerticalMargin) {
        this.mVerticalMargin = mVerticalMargin;
    }

    public int getmTextMaxLength() {
        return mTextMaxLength;
    }

    public void setmTextMaxLength(int mTextMaxLength) {
        this.mTextMaxLength = mTextMaxLength;
    }

    public int getmTextColor() {
        return mTextColor;
    }

    public void setmTextColor(int mTextColor) {
        this.mTextColor = mTextColor;
    }

    public int getmBordercolor() {
        return mBordercolor;
    }

    public void setmBordercolor(int mBordercolor) {
        this.mBordercolor = mBordercolor;
    }

    public float getmBorderRadius() {
        return mBorderRadius;
    }

    public void setmBorderRadius(float mBorderRadius) {
        this.mBorderRadius = mBorderRadius;
    }
}
